<?php
/*
 * @Author: your name
 * @Date: 2020-07-21 19:29:02
 * @LastEditTime: 2020-07-22 09:59:57
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \lemocms\app\admin\controller\Banner.php
 */

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\traits\Curd;
use FormBuilder\Factory\Elm;
use think\facade\Request;
use app\common\model\Banner as BannerModel;
use app\common\model\Attach;
use think\facade\View;

class Banner extends Backend
{

    use Curd;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->modelClass = new BannerModel();
    }

    /**
     * 轮播图列表渲染
     * @api {} /
     * @apiGroup
     * @apiParam {}
     * @Author mi
     * @DateTime 2020-07-22
     * @return void
     */
    public function index()
    {
        if (Request::isPost()) {
            $keys = $this->request->post('keys', '', 'trim');

            $where = [];
            if ($keys != '') {
                $where[] = ['title', 'like', '%' . $keys . '%'];
            }

            $page = $this->request->post('page');
            $limit = $this->request->post('limit');
            $tol = ($page - 1) * $limit;

            $banner = BannerModel::where($where)->limit($tol, $limit)->select();
            $count = BannerModel::where($where)->count();
            if (!$banner) error();
            success($banner, $count);
        }
        return view();
    }

    /**
     * @param $id
     * @return \think\response\View
     * @api {get} v1/goods/index 列表
     * @apiGroup 商品列表
     * @apiParam {int} id ID
     * @author mi
     */
    public function add()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            $res = BannerModel::create($data);
            if (!$res) error();
            $this->success('成功', url('banner/index'));
        }
        View::assign('info', null);
        return view();
    }

    public function edit($id)
    {
         if (Request::isPost()) {
             $data = $this->request->post();
             $res = BannerModel::update($data);
             if (!$res) error();
             $this->success('成功');
         }
         $banner = BannerModel::find(['id' => $id]);
         View::assign('info', $banner);
         return view('add');
    }

    public function del($id)
    {
        $banner = BannerModel::find($id);
        if (!$banner) error('轮播图查询失败');

        $attach = Attach::where(['path' => $banner['image']])->find();

//        if (!$attach) $this->errorMsg('未附件查询失败');

        if ($attach) if (!$attach->delete()) error();

        $path = substr($banner['image'], 1);
        if (file_exists($path)) unlink($path);//删除文件

        if (!$banner->delete()) error();

        $this->success('删除成功', '/');
    }
}
